<template>
	<div class="image_uploader">
		<el-upload
			ref="upload"
			:limit="1"
			:class="['upload_box', { hide: !!imageId }]"
			:action="uploadImgUrl"
			:on-success="handleUploadSuccess"
			:before-upload="handleBeforeUpload"
			:on-error="handleUploadError"
			:show-file-list="false"
			:headers="headers"
			:accept="uploadAccept"
			:data="uploadParams"
		>
			<el-button type="text" class="uploadBtn">上传图片</el-button>
		</el-upload>
		<div class="upload_img" v-if="!!imageId">
			<el-button-group>
				<el-button type="text" title="修改" icon="el-icon-edit" @click="handleAmendUpload()"></el-button>
				<el-button type="text" title="删除" icon="el-icon-delete" @click="handleDeleteImage()"></el-button>
			</el-button-group>
		</div>
	</div>
</template>

<script>
export default {
	props: {
		value: String,
		// 文件类型, 例如['png', 'jpg', 'jpeg']
		accept: {
			type: String,
			default: 'png,jpg,jpeg,webp'
		}
	},
	data() {
		const systemPath = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
		return {
			uploadImgUrl: `${systemPath}tbSysAttachment/upload`, // 上传的图片服务器地址
			headers: { Authorization: this.$session.get('token') },
			uploadParams: { showType: '1', type: '1' },
			imageId: this.value
		};
	},
	watch: {
		value(val) {
			this.imageId = val;
		},
		imageId(val) {
			this.$emit('input', val);
		}
	},
	computed: {
		uploadAccept() {
			let suffixArr = this.accept.split(',').map((item) => '.' + item);
			return suffixArr.join();
		},
		previewImage() {
			return [this.imageUrl];
		}
	},
	methods: {
		//修改上传
		handleAmendUpload() {
			this.$refs['upload'].$el.querySelector('.uploadBtn').click();
		},

		// 删除图片
		handleDeleteImage() {
			this.imageId = '';
		},

		// 上传前loading加载
		handleBeforeUpload(file) {},

		// 文件个数超出
		handleExceed() {
			this.$showCustomMessage('warning', `上传文件数量不能超过 ${this.limit} 个！`);
		},

		// 上传成功回调
		handleUploadSuccess(res, file) {
			if (res.code === '0') {
				let datas = !res.data ? {} : res.data[0];
				this.imageId = datas.id;
				this.imageUrl = datas.originalAddr;
			}
		},

		// 上传失败
		handleUploadError() {}
	}
};
</script>

<style lang="scss" scoped>
.image_uploader::v-deep {
	position: relative;

	.upload_box.hide {
		opacity: 0;
	}

	.el-upload {
		position: relative;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.upload_tip {
		color: #909399;
		font-size: 14px;
		line-height: 24px;
		margin-top: 6px;
	}

	.upload_img {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;

		.el-button {
			margin: 0 5px;
		}
	}
}
</style>
